#!/usr/bin/python
#-*- coding: utf-8 -*-

###########################################################
# Copyright 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Kitchen of Awesome.
#
# Kitchen of Awesome is free software: you can redistribute it and/or 
# modify it under the terms of the GNU General Public License 
# as published by the Free Software Foundation, either 
# version 3 of the License, or (at your option) any later 
# version.
#
# Kitchen of Awesome is distributed in the hope that it will be 
# useful, but WITHOUT ANY WARRANTY; without even the implied 
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
# PURPOSE. See the GNU General Public License for more details.
#
# You should have hreceived a copy of the GNU General Public 
# License along with Kitchen of Awesome. 
# If not, see http://www.gnu.org/licenses/.
###########################################################

import pymongo
from datetime import datetime

class Application():
	def __init__(self):
		con = pymongo.Connection()
		koadb = con.koa
		self.storage = koadb.storage
		setApplicationReference(self)

	def getStorage(self):
		return self.storage

	def run(self):
		pass


def setApplicationReference(app):
	global APPLICATION
	APPLICATION = app

APPLICATION = None

class KoaObject():
	CON = pymongo.Connection()
	FORBIDDEN_KEYWORDS = ["application","id"]
	@classmethod
	def load(cls,id):
		res = APPLICATION.getStorage().find_one({'_id':id})
		assert res is not None, "Object not Known"
		print res
		exec 'obj = '+res["_className"]+'()'
		dbid = res['_id']
		del(res['_id'])
		del(res['_className'])
		obj.__dict__ = res
		obj.id = dbid
		obj.application = APPLICATION
		return obj
	def __init__(self):
		self.id = None
		self.application = APPLICATION

	def _cleanDict(self,uncleanDict):
		for keyword in self.FORBIDDEN_KEYWORDS:
			if uncleanDict.has_key(keyword):
				del(uncleanDict[keyword])
		for key, el in uncleanDict.items():
			if type(el) not in (int,str,float,long,datetime):
				if hasattr(el,'id') and type(el.id) == pymongo.objectid.ObjectId:
					uncleanDict[key+'_id'] = el.id
				del(uncleanDict[key])
		return uncleanDict

	def store(self):
		saveDict = {}
		saveDict.update(self.__dict__)
		if self.id is None:
			saveDict['_className'] = self.__class__.__name__
			saveDict = self._cleanDict(saveDict)
			self.id = APPLICATION.getStorage().insert(saveDict)
		else:
			saveDict = self._cleanDict(saveDict)
			APPLICATION.getStorage().update({'_id':self.id},{'$set':saveDict})
		return self.id

	def __getattr__(self, name):
		if self.__dict__.has_key(name+'_id'):
			self.__dict__[name]=KoaObject.load(self.__dict__[name+'_id'])
			return self.__dict__[name]
		else:
			raise AttributeError()


class A(KoaObject):
	def __init__(self):
		KoaObject.__init__(self)
		self.blubbwert1 = None
		self.blubbwert2 = None
		self.b = None
	def onanie(self):
		print "ich onaniere"


class B(KoaObject):
	def __init__(self):
		KoaObject.__init__(self)
		self.blubbwert3 = None
		self.blubbwert4 = None
	def masturbation(self):
		print "ich masturbiere"

app = Application()
app.run()